
package com.chengyu.eyc.utils;

import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import org.springframework.util.Base64Utils;

import com.chengyu.eyc.exception.GenericException;

import lombok.extern.slf4j.Slf4j;


/**
 * Created by wk on 2017/2/14.
 */
@Slf4j
public final class RSAUtils {


	/**
	 * RSA最大加密明文大小
	 */
	private static final int MAX_ENCRYPT_BLOCK = 117;

	/**
	 * 私有的秘钥
	 */
	private static final String PRIVATE_KEY = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAJsc460y3DdjoRpzUakBvBGnIgy9fqFubCbyzaM1IwfdzzKZEMNXN8VuW4DdcqZ6bzUeEpyslm7T62nC/f17dPN9zL54DGlKvQhwlN0B04/3L3PaVzG0a7oGf7c1nNl/OnykP5+zdBkHhmb0hp+MpJ97QlDqb/mMDhx2SwId8r17AgMBAAECgYBvlSuvx5uleNVG+tgutSG+rTWQZqz2okHJDvehRbNqkETiSDxH2bE0JLxMioFUg1UGqBiJfppFJcv+7BfcxngNH362R4nLqc1eJiy7OMb72vZk6CAQs9QELfwkeUJRP5ZmugZBanikCjKuEZJWYP7LGhGuFBd2yPvDK43+V3i3+QJBAPkW8S5q+6wewsyWAdPSGjm8GXUl7Ox4A74/YWkkWR1da8NV/9ivcKpfHEvjielkC76hYz6w3c+Qq4vSWb/Ni6UCQQCfaoPxRxkeh0rUK/CVDP7PrY2b1zex+QA5KjSGzeGFZPDGFTFcHgRv0W+Bd8TsbT/oiuzNphqF4IAxwZbenVqfAkEA4FLt/5yvbJIDYxYRLT9BCQ/CaYMvPMLUtCgGRRdL/isdGry/fdh6AaVIKXwQvpSwEwzrARFtoTmrlG9rDlZBVQJBAJCIx0XLm3e1XF/P0tmgpapvhTOlRobi5pPtsyABrBYAddhyQIVvZcBn17w/ddiSGN5ijt7JWcTFzhTOm1YMvqsCQQDYzmy/eaZn9UZ5w/HHcnsbAKBrAYWyI+4OHsUpFrkHaez3Q/ntZiQv+SLfqg/JocidYpgXflqQ3F0zeqAvYPg4";

	/**
	 * 公有秘钥
	 */
	private static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCbHOOtMtw3Y6Eac1GpAbwRpyIMvX6hbmwm8s2jNSMH3c8ymRDDVzfFbluA3XKmem81HhKcrJZu0+tpwv39e3Tzfcy+eAxpSr0IcJTdAdOP9y9z2lcxtGu6Bn+3NZzZfzp8pD+fs3QZB4Zm9IafjKSfe0JQ6m/5jA4cdksCHfK9ewIDAQAB";

	private static final String RSA = "RSA";

	public static byte[] decryptData(byte[] encryptedData) {
		try {
			return decryptData(encryptedData, getPrivateKey(RSAUtils.PRIVATE_KEY));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return new byte[0];
	}

	/**
	 * 用私钥解密
	 *
	 * @param encryptedData
	 *            经过encryptedData()加密返回的byte数据
	 * @param privateKey
	 *            私钥
	 * @return
	 */
	private static byte[] decryptData(byte[] encryptedData, PrivateKey privateKey) {
		try {
			Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
			cipher.init(Cipher.DECRYPT_MODE, privateKey);
			return cipher.doFinal(encryptedData);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return new byte[0];
		}
	}

	private static byte[] encryptByPublicKey(String data, String key) {
		try {
			// 对公钥解密
			byte[] keyBytes = Base64Utils.decode(key.getBytes());
			// 取得公钥
			X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
			KeyFactory keyFactory = KeyFactory.getInstance(RSA);
			Key publicKey = keyFactory.generatePublic(x509KeySpec);
			// 对数据加密
			Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			return cipher.doFinal(data.getBytes());
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return new byte[0];
	}

	/**
	 * 用公钥加密 <br>
	 * 每次加密的字节数，不能超过密钥的长度值减去11
	 *
	 * @param data
	 *            需加密数据的byte数据
	 * @param publicKey
	 *            公钥
	 * @return 加密后的byte型数据
	 */
	public static byte[] encryptData(byte[] data, PublicKey publicKey) {

		try {
			Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
			// 编码前设定编码方式及密钥
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			// 传入编码数据并返回编码结果
			int inputLen = data.length;
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			int offSet = 0;
			byte[] cache;
			int i = 0;
			// 对数据分段加密
			while (inputLen - offSet > 0) {
				if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
					cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
				} else {
					cache = cipher.doFinal(data, offSet, inputLen - offSet);
				}
				out.write(cache, 0, cache.length);
				i++;
				offSet = i * MAX_ENCRYPT_BLOCK;
			}
			byte[] encryptedData = out.toByteArray();
			out.close();
			return encryptedData;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return new byte[0];
		}
	}

	public static byte[] encryptData(String data) {
		return encryptByPublicKey(data, PUBLIC_KEY);
	}

	/**
	 * 随机生成RSA密钥对(默认密钥长度为1024)
	 *
	 * @return
	 */
	public static KeyPair generateRSAKeyPair() {
		return generateRSAKeyPair(1024);
	}

	/**
	 * 随机生成RSA密钥对
	 *
	 * @param keyLength
	 *            密钥长度，范围：512～2048<br>
	 *            一般1024
	 * @return
	 */
	public static KeyPair generateRSAKeyPair(int keyLength) {
		try {
			KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
			kpg.initialize(keyLength);
			return kpg.genKeyPair();
		} catch (NoSuchAlgorithmException e) {
			log.error(e.getMessage(), e);
			return null;
		}
	}

	/**
	 * 通过私钥byte[]将公钥还原，适用于RSA算法
	 *
	 * @param keyBytes
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeySpecException
	 */
	public static PrivateKey getPrivateKey(byte[] keyBytes) throws NoSuchAlgorithmException, InvalidKeySpecException {
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(RSA);
		return keyFactory.generatePrivate(keySpec);
	}

	/**
	 * 从字符串中加载私钥<br>
	 * 加载时使用的是PKCS8EncodedKeySpec（PKCS#8编码的Key指令）。
	 *
	 * @param privateKeyStr
	 * @return
	 * @throws Exception
	 */
	private static PrivateKey getPrivateKey(String privateKeyStr) {
		try {
			byte[] buffer = Base64Utils.decodeFromString(privateKeyStr);
			PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
			KeyFactory keyFactory = KeyFactory.getInstance(RSA);
			return keyFactory.generatePrivate(keySpec);
		} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
			throw new GenericException("无此算法");
		}
	}

	/**
	 * 使用N、d值还原私钥
	 *
	 * @param modulus
	 * @param privateExponent
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeySpecException
	 */
	public static PrivateKey getPrivateKey(String modulus, String privateExponent)
			throws NoSuchAlgorithmException, InvalidKeySpecException {
		BigInteger bigIntModulus = new BigInteger(modulus);
		BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);
		RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
		KeyFactory keyFactory = KeyFactory.getInstance(RSA);
		return keyFactory.generatePrivate(keySpec);
	}

	/**
	 * 通过公钥byte[](publicKey.getEncoded())将公钥还原，适用于RSA算法
	 *
	 * @param keyBytes
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeySpecException
	 */
	public static PublicKey getPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException, InvalidKeySpecException {
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(RSA);
		return keyFactory.generatePublic(keySpec);
	}

	/**
	 * 从字符串中加载公钥
	 *
	 * @param publicKeyStr
	 *            公钥数据字符串
	 * @throws Exception
	 *             加载公钥时产生的异常
	 */
	public static PublicKey getPublicKey(String publicKeyStr) {
		try {
			byte[] buffer = Base64Utils.decodeFromString(publicKeyStr);
			KeyFactory keyFactory = KeyFactory.getInstance(RSA);
			X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
			return keyFactory.generatePublic(keySpec);
		} catch (NoSuchAlgorithmException e) {
			throw new GenericException("无此算法");
		} catch (InvalidKeySpecException e) {
			throw new GenericException("公钥非法");
		} 
	}

	/**
	 * 使用N、e值还原公钥
	 *
	 * @param modulus
	 * @param publicExponent
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeySpecException
	 */
	public static PublicKey getPublicKey(String modulus, String publicExponent)
			throws NoSuchAlgorithmException, InvalidKeySpecException {
		BigInteger bigIntModulus = new BigInteger(modulus);
		BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);
		RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
		KeyFactory keyFactory = KeyFactory.getInstance(RSA);
		return keyFactory.generatePublic(keySpec);
	}

	private RSAUtils() {

	}

}
